﻿/*
 * Copyright © 2025−2026 WEI.ZHOU (Willis) (Chengdu). All rights reserved.
 *
 * THIS SOURCE CODE IS PROPRIETARY AND CONFIDENTIAL.
 * It is the exclusive property of WEI.ZHOU (Willis) and may not be
 * used, copied, distributed, or disclosed outside of WEI.ZHOU (Willis)
 * without express written permission.
 *
 * This code is provided to WEI.ZHOU (Willis) under a limited, 
 * non-transferable internal license, and is for use only with the author's 
 * approved purposes. No external license is granted or implied.
 *
 * Any unauthorized use, reproduction, or distribution is strictly prohibited
 * and may result in severe civil and criminal penalties.
 */
 
using System.Text;

// ReSharper disable CollectionNeverQueried.Global

namespace Aore.Core.Repository.Dapper.Db.Contrib;

public class DbCondition
{
  public StringBuilder WhereClause { get; set; } = new StringBuilder();
  public Dictionary<string, object?> Parameters { get; set; } = new Dictionary<string, object?>();
  public List<string> OrderBy { get; set; } = new List<string>();
  public int? Skip { get; set; }
  public int? Take { get; set; }
  
  public DbCondition And(string condition, object? parameter = null, string paramName = null)
  {
    if (WhereClause.Length > 0)
      WhereClause.Append(" AND ");
        
    WhereClause.Append($"({condition})");
        
    if (parameter != null && !string.IsNullOrEmpty(paramName))
    {
      Parameters[paramName] = parameter;
    }
        
    return this;
  }

  public DbCondition Or(string condition, object? parameter = null, string paramName = null)
  {
    if (WhereClause.Length > 0)
      WhereClause.Append(" OR ");
        
    WhereClause.Append($"({condition})");
        
    if (parameter != null && !string.IsNullOrEmpty(paramName))
    {
      Parameters[paramName] = parameter;
    }
        
    return this;
  }

  public DbCondition OrderByAsc(string column)
  {
    OrderBy.Add($"{column} ASC");
    return this;
  }

  public DbCondition OrderByDesc(string column)
  {
    OrderBy.Add($"{column} DESC");
    return this;
  }

  public DbCondition Page(int page, int pageSize)
  {
    Skip = (page - 1) * pageSize;
    Take = pageSize;
    return this;
  }
}